package com.hopu.v1.controller.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.WriterException;
import com.hopu.v1.pojo.common.R;
import com.hopu.v1.utils.ZXingUtil;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

/**
 * 二维码生成代码
 */
@RestController
@RequestMapping("/qrcode")
public class QRCodeController {

    @GetMapping("generate")
    public R generateQRCode(@RequestParam String content, @RequestParam int width, @RequestParam int height) {
        try {
            // 生成二维码图片
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            String url = Objects.requireNonNull(getClass().getClassLoader().getResource("img/logo.png")).toString();
            System.out.println(url);

            ZXingUtil.encodeimage(out, "png", content, width, height, url); // 假设logo为null

            // 将图片转换为字节数组
            byte[] imageBytes = out.toByteArray();

            // 将字节数组转换为Base64字符串
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            // 打印Base64编码的图像数据
            System.out.println("Generated Base64 Image: " + base64Image);

            // 构建响应对象
            return R.ok("二维码生成成功", base64Image);
        } catch (WriterException | IOException e) {
            // 处理异常
            e.printStackTrace();
            return R.err("二维码生成失败: " + e.getMessage());
        }
    }
}